<template>
  <div class="tab-content">
    <div class="tab-panel">
      <h2>微博热搜榜</h2>
      <div v-if="weiboData.loading" class="loading">
        正在加载热搜...
      </div>
      <div v-else-if="weiboData.error" class="error">
        {{ weiboData.error }}
      </div>
      <div v-else class="weibo-content">
        <div class="weibo-list">
          <div class="weibo-item" v-for="(item, index) in weiboData.data" :key="index">
            <span class="rank">{{ index + 1 }}.</span>
            <span class="title">{{ item.title }}</span>
            <span class="hot" v-if="item.hot">热</span>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref, toRefs, watch } from 'vue';
import { API_BASE_URL } from '../utils/WebConstants.ts';

const props = defineProps<{
  refreshKey?: number;
}>();

const { refreshKey } = toRefs(props);

const weiboData = ref({
  loading: true,
  error: null as string | null,
  data: null as any,
});

// 获取微博热搜
const fetchWeibo = async () => {
  try {
    weiboData.value.loading = true;
    weiboData.value.error = null;
    const response = await fetch(`${API_BASE_URL}/weibo?encoding=text`);
    const result = await response.text();

    // 解析文本格式的微博热搜
    const lines = result.split('\n').filter((line) => line.trim() !== '');

    // 如果第一行是标题，移除它
    if (lines[0] && lines[0].includes('微博实时热搜')) {
      lines.shift();
    }

    // 将每行转换为对象格式
    weiboData.value.data = lines.map((line, index) => {
      // 移除行首的序号
      const content = line.replace(/^\d+\.\s*/, '');
      return {
        title: content,
        hot: index < 3, // 前3条标记为"热"
      };
    });
  } catch (err) {
    weiboData.value.error = '网络错误，请稍后重试';
    console.error('获取微博热搜时出错:', err);
  } finally {
    weiboData.value.loading = false;
  }
};

// 监听刷新键变化
watch(refreshKey, () => {
  fetchWeibo();
});

onMounted(() => {
  fetchWeibo();
});
</script>

<style scoped>
.tab-panel h2 {
  text-align: center;
  margin-bottom: 20px;
  color: white;
}

.loading, .error {
  text-align: center;
  padding: 40px 20px;
  font-size: 1.2rem;
}

.loading {
  color: #ccc;
}

.error {
  color: #d32f2f;
}

.weibo-list {
  background: #2d2d2d;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}

.weibo-item {
  padding: 12px 0;
  border-bottom: 1px solid #444;
  display: flex;
  align-items: center;
  gap: 10px;
}

.weibo-item:last-child {
  border-bottom: none;
}

.rank {
  font-weight: bold;
  color: #42b983;
  min-width: 30px;
}

.title {
  flex: 1;
  color: #ddd;
}

.hot {
  background-color: #ff4d4d;
  color: white;
  padding: 2px 6px;
  border-radius: 4px;
  font-size: 0.8rem;
}

@media (max-width: 768px) {
  .weibo-list {
    padding: 15px;
  }
  
  .weibo-item {
    padding: 8px 0;
    gap: 6px;
  }
}
</style>